package com.controller;


import com.entity.Role;
import com.service.RoleAuthorityService;
import com.service.RoleEmployeeService;
import com.service.RoleService;
import com.utils.PageObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author aiou
 * @since 2025-06-12
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleEmployeeService roleEmployeeService;

    @Autowired
    private RoleAuthorityService roleAuthorityService;

    @RequestMapping("/list")
    public String list(PageObject pageObject, Model model){
        model.addAttribute("page", this.roleService.roleList(pageObject));
        return "authorityList";
    }

    @PostMapping("/save")
    @ResponseBody
    public String save(Integer roleId,String roleName){
        if(roleId == null) {
            Role role = new Role();
            role.setRoleName(roleName);
            boolean save = this.roleService.save(role);
            if(save) return "success";
            return "fail";
        } else {
            Role role = new Role();
            role.setRoleId(roleId);
            role.setRoleName(roleName);
            boolean updateById = this.roleService.updateById(role);
            if(updateById) return "success";
            return "fail";
        }
    }

    @PostMapping("/delete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public String delete(@RequestParam("id") Integer roleId) throws Exception {
        //删除角色信息
        boolean removeById = roleService.removeByRoleId(roleId);
        if (!removeById) {
            throw new RuntimeException("删除角色失败");
        }
        //删除角色权限
        boolean remove = this.roleAuthorityService.removeByRoleId(roleId);
        if (!remove) {
            throw new RuntimeException("删除角色权限失败");
        }
        //删除角色员工关联信息
        boolean remove1 = this.roleEmployeeService.removeByRoleId(roleId);
        if (!remove1) {
            throw new RuntimeException("删除角色员工关联失败");
        }
        return "success";
    }

}

